package main

import (
	"fmt"
	"math/rand"
	"strconv"
	"time"
)

func f1(jobchan chan<- int) {
	rand.Seed(time.Now().UnixNano())
	for i := 0; i < 10; i++ {
		jobNum := rand.Intn(10) + 12
		jobchan <- jobNum
	}
	close(jobchan)
}

//将数转化为字符串切片，通过取切片中每个字符串得到每位数上的值
func f2(jobchan chan int, resultchan chan<- int) {
	var sum int
	for a := range jobchan {
		sum = 0
		numstr := strconv.Itoa(a)
		n := len(numstr)
		for i := 0; i < n; i++ {
			j, _ := strconv.Atoi(numstr[i : i+1])
			sum += j
		}
		resultchan <- sum
	}
	close(resultchan)
}

//使用除余法求得每位数上的值
func f3(jobchan chan int, resultechan chan<- int) {
	for a := range jobchan {
		var sum = 0
		for {
			if a/10 != 0 {
				sum += a % 10
				a = a / 10
			} else {
				sum += a
				break
			}
		}
		resultechan <- sum
	}
	close(resultechan)
}

func main() {
	jobchan := make(chan int, 50)
	resultchan := make(chan int)
	go f1(jobchan)
	go f3(jobchan, resultchan)
	for i := range resultchan {
		fmt.Println(i)
	}
}
